<?php

namespace App\Http\Controllers;
use DB;
use Illuminate\Http\Request;

class SettingController extends Controller
{
    public function permission(Request $request)
    {
        $data['title'] = '权限管理';
        $name = $request->input('name');
        if ($name)
        {
            $data['menu'] = DB::table('permissions')->select('*')->where([
                ['name', 'like', $name.'%'],
                ['name', '!=', $name]
            ])->get();
        }
        else
        {
            $data['menu'] = DB::table('permissions')->select('*')->where([
                ['is_menu', 1],
            ])->orderBy('sort','asc')->get();
        }
        return view('setting.menu', $data);
    }

    public function ajax(Request $request)
    {
        $id = $request->input('id');
        $data['ack'] = false;
        if ($id)
        {
            $update = [];
            if ($request->input('status')) $update['status'] = $request->input('status') == 'true' ? 1 : 0;
            if ($update) DB::table('permissions')->where('id', $id)->update($update);
            $data['ack'] = true;
        }
        return response()->json($data);
    }

    public function role(Request $request)
    {
        $data['title'] = '角色管理';
        $data['role'] = DB::table('roles')->select('*')->get();
        $where = [];
        if($request->input('id')) $where['id'] =  $request->input('id');
        $data['roles'] = DB::table('roles')->select('*')->where($where)->orderBy('id', 'desc')->paginate(5);
        $data['roles']->appends($where)->render();
        return view('setting.role', $data);
    }

    public function rolecreate(Request $request)
    {
        $data['title'] = '新建角色';
    }

    public function log(Request $request)
    {
        $data['title'] = '操作日志';
        $data['users'] = DB::table('users')->select('*')->where('status', 1)->get();
        $where = $page = [];
        if($request->input('start'))
        {
            $start = date('Y-m-d 00:00:00', strtotime($request->input('start')));
            $where[] = ['time', '>=', $start];
            $page['start'] = substr($start, 0 ,10);
        }
        if($request->input('end'))
        {
            $end = date('Y-m-d 23:59:59', strtotime($request->input('end')));
            $where[] = ['time', '<=', $end];
            $page['end'] = substr($end, 0 ,10);
        }
        if($request->input('user_id'))
        {
            $where[] = ['user_id', $request->input('user_id')];
            $page['user_id'] =  $request->input('user_id');
        }
        $data['logs'] = DB::table('users_log')->select('*')->where($where)->orderBy('id', 'desc')->paginate(5);
        $data['logs']->appends($page)->render();
        return view('setting.log', $data);
    }

    public function crontab()
    {
        $data['title'] = '定时任务';
    }

    public function weixin()
    {
        $data['title'] = '微信设置';
    }
}
